package com.nlx.notes.support.handler.exception;

import com.nlx.notes.module.bean.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.ErrorResponse;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    // 处理所有 Exception 异常
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultVO<?> handleException(Exception ex) {
        log.error("异常信息 ->",ex);
        return ResultVO.error(500, "服务器内部异常");
    }

    // 自定义处理特定异常，比如 IllegalArgumentException
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultVO<?> handleIllegalArg(IllegalArgumentException ex) {
       return ResultVO.error(400, "参数异常:"+ex.getMessage());
    }

    @ExceptionHandler(BusinessException.class)
    public ResultVO<?> handleBusinessException(BusinessException ex) {
        return ResultVO.error(ex.getCode(), ex.getMessage());
    }

    /**
     * 处理参数校验异常
     * @param ex MethodArgumentNotValidException
     * @return ResultVO
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultVO<Map<String, String>> handleValidationException(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            return ResultVO.error(400, fieldError.getDefaultMessage());
        }
        return  ResultVO.error(400, "参数校验失败");
    }


}
